using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;

public class AstarAI : MonoBehaviour
{
    public float randomRadius;  //监测范围
    public float speed = 2; //
    public float nextWayPointDistance;  //距离
    public bool reachedEndOfPath;   //是否到达路线终点

    [HideInInspector] public Vector3 nextTargetPosition;
    private Seeker seeker;
    private Path path;
    private int currentWayPoint = 0;
    private Vector3 targetLastPosition;
    
    // public Transform targetPosition;
    
    void Awake()
    {
        seeker = GetComponent<Seeker>();
    }

    private void OnPathComplete(Path p)
    {
        Debug.Log("Master, we got a path back. Did it have an error? " + p.error);

        if (!p.error)
        {
            path = p;
            currentWayPoint = 0;
        }
    }

    public void UpdatePath(Vector2 targetPosition)
    {
        if (Vector2.Distance(targetPosition, targetLastPosition) > 1)
        {
            targetLastPosition = targetPosition;
            seeker.StartPath(transform.position, targetPosition, OnPathComplete);
        }
    }

    public void RandomPath()
    {
        var point = Random.insideUnitSphere * randomRadius;
        point += transform.position;
        
        UpdatePath(point);
    }

    public void NextTarget()
    {
        if (path == null)
        {
            return;
        }

        reachedEndOfPath = false;

        float distanceToWayPoint;
        while (true)
        {
            distanceToWayPoint = Vector3.Distance(transform.position, path.vectorPath[currentWayPoint]);
            if (distanceToWayPoint < nextWayPointDistance)
            {
                if (currentWayPoint + 1 < path.vectorPath.Count)
                {
                    currentWayPoint++;
                }
                else
                {
                    reachedEndOfPath = true;
                    break;
                }
            }
            else
            {
                break;
            }
        }
        
        var speedFactor = reachedEndOfPath ? Mathf.Sqrt(distanceToWayPoint / distanceToWayPoint) : 1f;
        if (!reachedEndOfPath)
        {
            nextTargetPosition = path.vectorPath[currentWayPoint];
            Vector3 dir = (nextTargetPosition - transform.position).normalized;
            Vector3 velocity = dir * speed * speedFactor;
            transform.position += velocity * Time.deltaTime;
        }
        else
            path = null;
    }
}
